package com.yeskery.nut.extend.memory;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 默认的基于内存的存储接口
 * @author sprout
 * @version 1.0
 * 2022-06-03 11:36
 */
public class DefaultStorage implements Storage, Externalizable {

    /** 序列化版本 */
    private static final long serialVersionUID = 1L;

    /** 数据map */
    private Map<String, Object> dataMap = new ConcurrentHashMap<>();

    @Override
    public boolean set(String key, Object value) {
        if (key == null || value == null) {
            throw new IllegalArgumentException("Key Or Value Must Not Be Null.");
        }
        return dataMap.put(key, value) != null;
    }

    @Override
    public Object get(String key) {
        if (key == null) {
            throw new IllegalArgumentException("Key Must Not Be Null.");
        }
        return dataMap.get(key);
    }

    @Override
    public boolean remove(String key) {
        if (key == null) {
            throw new IllegalArgumentException("Key Must Not Be Null.");
        }
        return dataMap.remove(key) != null;
    }

    @Override
    public boolean clear() {
        dataMap.clear();
        return true;
    }

    @Override
    public boolean isEmpty() {
        return dataMap.isEmpty();
    }


    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(dataMap);
    }

    @Override
    @SuppressWarnings("unchecked")
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        dataMap = (Map<String, Object>) in.readObject();
    }
}
